package com.ggb.reactive.security

import lombok.AllArgsConstructor
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.context.SecurityContext
import org.springframework.security.core.context.SecurityContextImpl
import org.springframework.security.web.server.context.ServerSecurityContextRepository
import org.springframework.stereotype.Component
import org.springframework.web.server.ServerWebExchange
import reactor.core.publisher.Mono

@Component
@AllArgsConstructor
class SecurityContextRepository(val jwtAuthenticationManager: JwtAuthenticationManager): ServerSecurityContextRepository {
    override fun save(exchange: ServerWebExchange?, context: SecurityContext?): Mono<Void> {
        return Mono.empty()
    }

    override fun load(exchange: ServerWebExchange?): Mono<SecurityContext> {
        println("访问 ServerSecurityContextRepository  。。。。。。。。。。。")
        val token = exchange?.getAttribute<String>("token") ?: return Mono.empty()
        return jwtAuthenticationManager.authenticate(UsernamePasswordAuthenticationToken(token, token))
            .map { SecurityContextImpl(it) }

        }
}